<template>
  <div class="mail-list-container">
    <h1>消息列表</h1>
    <div v-if="mails.length === 0" class="no-mails">
      暂无警告消息
    </div>
    <div v-else class="mail-list">
      <div v-for="mail in mails" :key="mail.id" class="mail-item">
        <p><strong>报警消息:</strong> {{ mail.message }}</p>
        <p><strong>报警时间:</strong> {{ formatDate(mail.sendTime) }}</p>
      </div>
    </div>
  </div>
</template>

<script>
import { fetchMails } from '@/api/mailList/mailList';

export default {
  data() {
    return {
      mails: [],
      timer: null,
    };
  },
  created() {
    this.fetchMailsData();
    this.timer = setInterval(this.fetchMailsData, 5000); // 每5秒刷新一次
  },
  beforeDestroy() {
    clearInterval(this.timer); // 清除定时器
  },
  methods: {
    async fetchMailsData() {
      try {
        const response = await fetchMails();
        this.mails = response.sort((a, b) => new Date(b.sendTime) - new Date(a.sendTime));
      } catch (error) {
        console.error('获取邮件列表失败:', error);
      }
    },
    formatDate(date) {
      const options = {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      };
      return new Date(date).toLocaleDateString('zh-CN', options);
    },
  },
};
</script>

<style scoped>
.mail-list-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  font-family: Arial, sans-serif;
  background-color: #f4f4f9;
}

h1 {
  margin-bottom: 20px;
}

.mail-list {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 80%;
  max-width: 600px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.mail-item {
  border-bottom: 1px solid #ddd;
  padding: 10px 0;
  width: 100%;
  text-align: left;
}

.mail-item:last-child {
  border-bottom: none;
}

.no-mails {
  margin-top: 20px;
  font-size: 18px;
  color: #555;
}
</style>
